//
//  NetworkTools.swift
//  weibo 666
//
//  Created by mac on 15/11/7.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
enum WCYRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    //创建应用程序建立的，不可以修改，相当于身份证
    private let appKey = "1636079617"
    //用来识别应用的，可以改
    private let appSecret = "2824c4eed7a066cea0bfc960a56bc310"
    
    //自己设置的，也是用来识别应用程序的
    private let redirect_uri = "http://www.baidu.com"
    
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias WCYRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    //单例
    static let sharedTools: NetworkTools = {
    
        let tools = NetworkTools(baseURL: nil)
        
//        设置反序列化
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    /// 返回 token 字典
    private var tokenDict: [String: AnyObject]? {
        // 判断 token 是否有效
        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
            
            return ["access_token": token]
        }
        
        return nil
    }
    
}
//MARK: - 用户信息
extension NetworkTools {
    
    /// - see[http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo (uid: String, finished: WCYRequestCallBack){
        
        //获取token的字典
        guard var params = tokenDict else {
            
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }

        let urlString = "https://api.weibo.com/2/users/show.json"
        
        params["uid"] = uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
        
    }
}


// MARK: - 相关的OAuth方法
extension NetworkTools {

    var oauth: NSURL{
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: WCYRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    }

    
    
}
extension NetworkTools {
    
    ///加载微博数据
    func loadStatus(finished: WCYRequestCallBack) {
        guard let params = tokenDict else{
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        //处理网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //发起网络请求
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}


// MARK: - 封装AFN网络
extension NetworkTools {
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    private func request(method: WCYRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: WCYRequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == WCYRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
        
        
    }
}

